package redis;


import java.io.IOException;

import com.herohead.redis.GetRedisServer;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisMonitor;

public class TestMontior {

	public static String redisHost;
	
	
	public static void main(String[] args) throws IOException, InterruptedException {
//		Config poolConfig = new Config();
//		final JedisPool jedisPool = new JedisPool(poolConfig, "localhost", 6379); 
		
		GetRedisServer grs = new GetRedisServer();
		redisHost = grs.getRedisHost();
		Jedis jedisOps = new Jedis(redisHost, 6379);
		try {
			Thread t = new Thread(new MonitorThread());
			t.start();
			//jedisOps.set("one", "1");
			//jedisOps.get("one");
			//jedisOps.set("two", "2");
			//jedisOps.exists("one");
			//jedisOps.dbSize();
			//jedisOps.disconnect();
			t.join();
		}
		finally {
			jedisOps.disconnect();
		}
		System.out.println("\nDone");
	}
}


class MonitorThread implements Runnable {
	
	private boolean stopThread = false;
	private Jedis jedisMonitor;
	private MonitorCommands monitorCommands;
	
	public MonitorThread() {
		GetRedisServer grs = new GetRedisServer();
		String redisHost = grs.getRedisHost();
		jedisMonitor = new Jedis(redisHost, 6379);
		monitorCommands = new MonitorCommands(this);
	}
	
	public void run(){
		try {
			while(!stopThread)
				jedisMonitor.monitor(monitorCommands);
		}
		finally {
			jedisMonitor.disconnect();
		}
	}
	
	public void setStopThread(boolean st) {
		stopThread = st;
	}
}

class MonitorCommands extends JedisMonitor {
	
	private MonitorThread monitorThread;
	
	public MonitorCommands(MonitorThread mt) {
		monitorThread = mt;
	}
	
	public void onCommand(String command) {
		System.out.println("Received: " + command);
		if(command.contains("DBSIZE"))
			monitorThread.setStopThread(true);
	}
}
